package com.finance.cooperate.dao.log;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.finance.cooperate.common.properties.CooperateProperties;
import com.finance.cooperate.common.utils.SpringContextUtil;
import com.finance.cooperate.dao.entity.secondary.LogError;
import com.finance.cooperate.dao.local.scope.CooperateRequestScope;
import com.finance.cooperate.dao.repository.secondary.LogErrorRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

/**
 * @ClassName SendErrorDBAppender
 * @Description 错误日志保存到DB
 * @Author shen
 * @Date 2022/6/8 10:58
 * @Modify ...
 */
@Slf4j
public class SendErrorDBAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
    @Override
    protected void append(ILoggingEvent event) {
        CooperateProperties cooperateProperties = (CooperateProperties) SpringContextUtil
                .getApplicationContext().getBean("cooperateProperties");


        LogErrorRepository logErrorRepository = (LogErrorRepository) SpringContextUtil
                .getApplicationContext().getBean("logErrorRepository");


        CooperateRequestScope cooperateRequestScope = (CooperateRequestScope) SpringContextUtil
                .getApplicationContext().getBean("cooperateRequestScope");



        if (event.getLevel() == Level.ERROR && !cooperateProperties.getEnvironment().getIsDebug()) {

            IThrowableProxy iThrowableProxy = event.getThrowableProxy();

            StringBuilder sb = new StringBuilder();

            if (iThrowableProxy != null && iThrowableProxy instanceof ThrowableProxy) {
                ThrowableProxy throwableProxy = (ThrowableProxy) iThrowableProxy;
                Throwable throwable = throwableProxy.getThrowable();
                String throwableMsg = throwable.getMessage();

                StackTraceElementProxy[] stackTraceElementProxy = iThrowableProxy.getStackTraceElementProxyArray();

                sb.append(event.getMessage()).append("\n");
                if (StringUtils.isNotEmpty(throwableMsg)) {
                    sb.append(throwableMsg).append("\n");
                }
                int i = 0;
                for (StackTraceElementProxy proxy : stackTraceElementProxy) {
                    //只打印40行的堆栈
                    if (i < 40) {
                        sb.append(proxy.getSTEAsString()).append("\n");
                    } else {
                        break;
                    }
                    i++;
                }
            } else {
                sb.append(event.getMessage());
            }

            String msg = sb.toString();

            if (StringUtils.isNotEmpty(msg)) {

                // 保存数据

                LogError error = new LogError();
                error.setUid(cooperateRequestScope.getUserId());
                error.setApplyId(cooperateRequestScope.getApplyId());
                error.setLoanNum(cooperateRequestScope.getLoanNum());
                error.setProject(cooperateProperties.getEnvironment().getProject());
                error.setLog(msg);

                try {
                    logErrorRepository.save(error);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }

    }
}
